Heads up about the way I code:
# Load packages
library(tidyverse) # readr (read_csv and other data loading functions), dplyr (select, filter, mutate, and other data wrangling functions), magrittr (the piping function), ggplot2 (everything dataviz)
library(plotly) # making interactive graphs (ggplotly())
library(htmlwidgets) # Exporting graphs as HTML (saveWidget())
# Load data
penguins <- read_csv("penguins.csv")Same data set as last week: Palmer Penguin dataset from LTER data.
# I like to run all these in the console or comment them out after running
#View(penguins) # Can also click on the object in the global environment
str(penguins) #shows the structure of the dataset## tibble [344 x 8] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
## $ species : chr [1:344] "Adelie" "Adelie" "Adelie" "Adelie" ...
## $ island : chr [1:344] "Torgersen" "Torgersen" "Torgersen" "Torgersen" ...
## $ bill_length_mm : num [1:344] 39.1 39.5 40.3 NA 36.7 39.3 38.9 39.2 34.1 42 ...
## $ bill_depth_mm : num [1:344] 18.7 17.4 18 NA 19.3 20.6 17.8 19.6 18.1 20.2 ...
## $ flipper_length_mm: num [1:344] 181 186 195 NA 193 190 181 195 193 190 ...
## $ body_mass_g : num [1:344] 3750 3800 3250 NA 3450 ...
## $ sex : chr [1:344] "male" "female" "female" NA ...
## $ year : num [1:344] 2007 2007 2007 2007 2007 ...
## - attr(*, "spec")=
## .. cols(
## .. species = col_character(),
## .. island = col_character(),
## .. bill_length_mm = col_double(),
## .. bill_depth_mm = col_double(),
## .. flipper_length_mm = col_double(),
## .. body_mass_g = col_double(),
## .. sex = col_character(),
## .. year = col_double()
## .. )
## # A tibble: 5 x 8
## species island bill_length_mm bill_depth_mm flipper_length_~ body_mass_g sex
## <chr> <chr> <dbl> <dbl> <dbl> <dbl> <chr>
## 1 Chinst~ Dream 55.8 19.8 207 4000 male
## 2 Chinst~ Dream 43.5 18.1 202 3400 fema~
## 3 Chinst~ Dream 49.6 18.2 193 3775 male
## 4 Chinst~ Dream 50.8 19 210 4100 male
## 5 Chinst~ Dream 50.2 18.7 198 3775 fema~
## # ... with 1 more variable: year <dbl>
REVIEW: Create a scatterplot using ggplot.
body_mass_gbill_length_mmspeciesHint: Use ggplot, geom_point, and aes(color = "")
Tips:
ggplot2 is the package, ggplot is the functionggplot() or any geom_*ggplot(data = penguins,
aes(x = body_mass_g, y = bill_length_mm,
color = species, shape = sex)) +
geom_point(na.rm = TRUE) # suppresses warning code about removed NAsTips:
# Make the plot pretty!
# Save a vector of colors for use in future graphs
col_scale <- c("#A3E7FC", "#32908F", "#26C485") # c() combines values into a vector
names(col_scale) <- c("Adelie", "Gentoo", "Chinstrap") # naming each value to correspond to the species
# Save a vector of names for use in the legend
lab_scale <- c("P. adeliae", "P. papua", "P. antarcticus") #scientific names :)
names(lab_scale) <- c("Adelie", "Gentoo", "Chinstrap") #ALWAYS name your vectors and double check the order
# New pretty graph
p <- penguins %>%
na.omit() %>% # removes ALL lines with NAs from dataset
ggplot(aes(x = body_mass_g/1000, # can divide by 1000 to make units more manageable
y = bill_length_mm,
color = species, # point color depends on species
shape = sex)) + # point shape depends on sex
geom_point(size = 1.5, # adjust point size
stroke = 1.1) + # adjust outline line width
# scale_color_manual(values = "red", "yellow", "green")) + # DOESN'T WORK
# scale_color_manual(values = c("lightskyblue", "slateblue4", "darkslategray4")) +
scale_color_manual(values = col_scale,
labels = lab_scale, # order matters (unless you use a named vector!)
name = "Species") +
# scale_shape_manual(values = c("\u2600", "\u2601")) + # using unicode values
# scale_shape_manual(values = c("\u2640", "\u2642")) + #another unicode option
scale_shape_manual(values = c(19, 21), #base R shapes
name = "Sex") + #legend title
theme_minimal() + # one of the default themes
theme(text = element_text(color = "grey80"), # ALL text color
title = element_text(face = "bold"), # all TITLES to bold
plot.title = element_text(color = "lightblue", # PLOT TITLE color
size = 16, # PLOT TITLE text size
hjust = 0.5, vjust = 5), # adjusting title positioning
plot.margin = margin(25,15,10,10), # remember TRBL (trouble)
axis.text = element_text(color = "grey70"), # AXIS LABELS color
legend.text = element_text(face = "italic"), # LEGEND LABELS color
legend.background = element_rect(fill = "grey25", # LEGEND BACKGROUND color
color = NA), # no legend outline
plot.background = element_rect(fill = "grey20"), # entire background color
panel.grid = element_line(color = "grey60")) + # GRID LINE color
labs(x = "Body mass (kg)", # Make sure units match!!! Especially after converting
y = "Bill length (mm)",
title = "IncrediBILL Palmer Penguins")
p #view the named plotLike your theme and want to use it for another graph without copy-pasting? Save it!
theme_set replaces the defaulttheme_update adds new elements to the default theme (analagous to +)theme_replace replaces elements of the default theme# Set the default as one of the included themes
theme_set(theme_classic())
#Check it out
ggplot(cars, aes(x = speed, y = dist)) + geom_point()# Make your own theme!
theme_awful <- theme_dark() # save a copy of a default theme with a new name
theme_set(theme_awful) # set your copy as the default
theme_update(panel.grid.minor = element_line(colour = "red", size = 3), #update your copy!
plot.background = element_rect(fill = "yellow"),
title = element_text(size = 60, face = "italic", color = "tan"),
axis.text = element_text(color = "purple", face = "bold", angle = 160))
#Check your new default theme out
ggplot(cars, aes(x = speed, y = dist)) + geom_point()# Check filepath
getwd() # usually run in the console - check where on your computer the plot will be saved## [1] "C:/Users/carol/Documents/R/tidytuesday-06oct2020"
ggsave("penguin_plot.png", # filepath will be added to WD path (prob just filename) - INCLUDE FILE TYPE EXTENSION.
plot = p, # name of object to save - default is last_plot()
height = 4, width = 5, units = "in") # output size (can use inches, cm, pixels)Plotly
REVIEW: Create a scatterplot using ggplot.
flipper_length_mmbody_mass_gspecies, same color scheme as above (use the saved vector!)theme_set(theme_classic()) # switching defaults since I'm not a huge fan of theme_awful...
ggplot(penguins, aes(x = flipper_length_mm, y = body_mass_g,
color = species)) +
geom_point(na.rm=TRUE) + # suppress warning about NAs being removed
scale_color_manual(values = col_scale) # same color vector as previous graph!Tips:
The following aesthetic parameters will stay nice when you run your graph through Plotly:
ggplot(penguins, aes(x = flipper_length_mm/10, y = body_mass_g/1000, # adjust units
fill = species)) + # changes INSIDE color of the point
geom_point(na.rm = TRUE,
shape = 21, # this particular shape allows for a color AND a fill
color = "grey30") + # changes OUTSIDE color of the point
scale_fill_manual(values = col_scale, # use scale_fill_* because we used "fill" in the aes
name = "Species") +
labs(x = "Flipper length (cm)", # match units!
y = "Body mass (kg)", # match units!
title = "Flippin' Palmer Penguins")# Updated static plot
p2 <- ggplot(penguins, aes(x = flipper_length_mm/10, y = body_mass_g/1000,
fill = species,
cooltip = sex)) + # text to use for tooltip - can have any name
geom_point(na.rm = TRUE,
size = 2, shape = 21, color = "grey30") +
scale_fill_manual(values = col_scale,
name = "Species") +
theme_classic() +
labs(x = "Flipper length (cm)",
y = "Body mass (kg)",
title = "Flippin' Palmer Penguins")
# Interactive plot
ggplotly(p2,
tooltip = "cooltip") # changes tooltip text. Remember - you can add any data column to the tooltip as long as you name it in aes()This is ideal for timeseries data - especially measurements that are paired between years.
# Updated static plot
p3 <- ggplot(penguins, aes(x = flipper_length_mm/10, y = body_mass_g/1000,
fill = species,
cooltip = sex,
frame = year)) + # adds animation, with one frame per year
geom_point(na.rm = TRUE,
size = 2, shape = 21, color = "grey30") +
scale_fill_manual(values = col_scale,
name = "Species") +
theme_classic() +
labs(x = "Flipper length (cm)",
y = "Body mass (kg)",
title = "Flippin' Palmer Penguins")
# Interactive plot
p3_move <- ggplotly(p3,
tooltip = "cooltip")
p3_moveSave as HTML
htmltools# Save as standalone HTML
saveWidget(p3_move, "penguin_animation.html") #this function is from the htmlwidget packageExport to plotly account
# Save plotly username and API key
Sys.setenv("plotly_username" = "katekathrynkat")
Sys.setenv("plotly_api_key" = "WmLiHIWtsIoNpfMz96a6")
# Explort plot to plotly
api_create(x = p3_move, # name of plot
fileopt = "overwrite", sharing = "public")See Kate’s embeddable graph: https://chart-studio.plotly.com/~katekathrynkat/39/#/
-Scroll to bottom right -There are 4 icons: Facebook, Twitter, link, <> -The <> icon will bring up the code you can give to a webmaster or embed on an html page